package com.cmge.ad.spider.article.waduanzi;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import com.cmge.ad.model.Article;
import com.cmge.ad.spider.pipeline.MysqlArticlePipeline;

/**
 * @desc	挖段子笑话	
 * 			http://www.waduanzi.com/mobile
 * @author	ljt
 * @time	2014-12-29 上午11:16:05
 */
public class WaJokePageProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(100);

    public static final String URL_LIST = "/mobile/joke/page/\\w+";
    
    // 列表最大值
    private int max = 2151;
    
    private boolean flag = true;
    
    @Override
    public void process(Page page) {
    	// 检索当前页面所有段子
    	List<Selectable> cList = page.getHtml().xpath("//div[@class='panel panel10 post-item post-box']").nodes();
    	List<Article> articleList = new ArrayList<Article>();
		if(null != cList && cList.size() > 0){
			for(Selectable str : cList){
				Article article = new Article();
				String content = str.xpath("//div[@class='item-content']/text()").get();
				String minUrl = str.xpath("//div[@class='post-image']//img[@class='bmiddle']/@src").get();
				String maxUrl = str.xpath("//div[@class='post-image']//a/@data-bmiddle-url").get();

				article.setSource("waduanzi_duanzi");
				article.setContent(content.trim());
				article.setMaxImageUrl(maxUrl);
				article.setMinImageUrl(minUrl);
				// 如果内容和图片都为空  则不需要保存
				if(!StringUtils.isEmpty(content) || !StringUtils.isEmpty(minUrl)){
					articleList.add(article);
				}
				if(StringUtils.isEmpty(maxUrl) && StringUtils.isEmpty(minUrl)){
	        		article.setType(1);
	        	}else{
	        		article.setType(2);
	        	}
    		}
			page.putField("articleList",articleList);
			page.putField("type", 1);
		}
		
		if(flag){
			for(int i = 2;i<max;i++){
				page.addTargetRequest("http://www.waduanzi.com/mobile/joke/page/"+i);
			}
			flag = false;
		}
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) throws Exception {
    	Spider qsSpider = Spider.create(new WaJokePageProcessor())
    					.addUrl("http://www.waduanzi.com/mobile/joke/page/1")
//    					.addPipeline(new RedisPipeline())
//    					.addPipeline(new JsonFilePipeline())
    					.addPipeline(new MysqlArticlePipeline())
    					.thread(1);
    	qsSpider.start();
    }
}
